// dia2dump.cpp : Dump contents of a pdb file using DIA.
//
//       Copyright (c) Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------
//
#include "stdafx.h"
#include <string>
#include <iostream>

void trim( std::string& s_in, std::string& s_out )
{
	const char * pstart = s_in.c_str();
	const char * ptail = pstart + s_in.size();
	while( pstart < ptail && isspace(*pstart) ) ++ pstart;
	while( ptail > pstart && isspace(*ptail) ) -- ptail;
	s_out.assign( pstart, ptail );
}

bool get_pdb_url( const char * file, std::string & url, std::string & lname )
{
	if( !file ) return false;

	CHAR szPdbFile[MAX_PATH] = {};
	CHAR szGuid[128] = {};

	SYMSRV_INDEX_INFO Info = {};
	Info.sizeofstruct = sizeof(Info);
	if( !SymSrvGetFileIndexInfo( file, &Info, 0 ) )
		return false;

	size_t len = strlen(Info.pdbfile);
	if( len > MAX_PATH-1 ) return false;

	strcpy( szPdbFile, Info.pdbfile );
	szPdbFile[len-1] = '_';

	url = "http://msdl.microsoft.com/download/symbols/" ;
	url += Info.pdbfile;
	url += "/";

	sprintf( szGuid, "%08X%04X%04X%02X%02X%02X%02X%02X%02X%02X%02X%X", 
		Info.guid.Data1, Info.guid.Data2, Info.guid.Data3, 
		Info.guid.Data4[0], Info.guid.Data4[1],
		Info.guid.Data4[2], Info.guid.Data4[3],
		Info.guid.Data4[4], Info.guid.Data4[5],
		Info.guid.Data4[6], Info.guid.Data4[7],
		Info.age );

	url += szGuid;
	url += "/";
	url += szPdbFile;

	lname = szGuid;
	lname.append( "." );
	lname.append( Info.pdbfile );

	return true;
}

int main( int argc, char ** argv )
{
	PVOID oldp = 0;
	Wow64DisableWow64FsRedirection( &oldp );

	printf( "md pdbs\nmd cabs\n" );

	if( argc < 2 )
	{
		while( 1 )
		{
			std::string line, lname;

			std::cin >> line;

			if( !get_pdb_url( line.c_str(), line, lname ) )
				continue;

			printf( "wget -U Microsoft-Symbol-Server/6.11.0001.402 %s -O cabs/%s\n", line.c_str(), lname.c_str() );
			printf( "expand cabs/%s -F:Files pdbs\n", lname.c_str() );

		};
	}
	else
	{
		for( size_t i = 1; i < argc; ++ i )
		{
			std::string url, lname;

			if( !get_pdb_url( argv[i], url, lname ) )
				continue;

			printf( "wget -U Microsoft-Symbol-Server/6.11.0001.402 %s -O cabs/%s\n", url.c_str(), lname.c_str() );
			printf( "expand cabs/%s -F:Files pdbs\n", lname.c_str() );
		}
	}

	return 0;
}